package es.upv.tricia.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import es.upv.tricia.QuestionCategory;
import es.upv.tricia.QuestionCategorySet;
import es.upv.tricia.R;
import es.upv.tricia.Tricia;

public class SettingsActivity extends Activity
{
	private static final int QUESTION_CATS_DIALOG = 0;

	private SharedPreferences mPrefs;

	private SharedPreferences.Editor mEdit;

	private TextView mNameField;

	private TextView mEmailField;

	private TextView mAddFriendField;

	private Spinner mServerSpinner;

	private QuestionCatsDialog mQuestionCatsDialog;

	private String mEmail;

	private String mFriendMail;

	private static final String BASE_URL = "http://dakkon.disca.upv.es:8080/";

	private class QuestionCatsDialog implements
			DialogInterface.OnClickListener,
			DialogInterface.OnMultiChoiceClickListener
	{
		private QuestionCategorySet mSelection;
		private TextView mQuestionCatsText;

		private QuestionCatsDialog(QuestionCategorySet selection)
		{
			this.mSelection = selection;
			mQuestionCatsText = (TextView) findViewById(R.id.questionCatsText);

			update();
		}

		public QuestionCategorySet getSelection()
		{
			return mSelection;
		}

		@Override
		public void onClick(DialogInterface dialog, int which, boolean isChecked)
		{
			QuestionCategory cat = QuestionCategory.values()[which];

			if (isChecked) {
				mSelection.add(cat);
			} else {
				mSelection.remove(cat);
			}
		}

		@Override
		public void onClick(DialogInterface dialog, int which)
		{
			mEdit.putString("questionCats", mSelection.serialize());
			mEdit.commit();

			update();
		}

		private void update()
		{
			if (mSelection.size() > 0) {
				mQuestionCatsText.setText(R.string.questionCatsTextSet);
			} else {
				mQuestionCatsText.setText(R.string.questionCatsTextNotSet);
			}
		}

		public AlertDialog build()
		{
			QuestionCategory[] cats = QuestionCategory.values();
			boolean checked[] = new boolean[cats.length];
			for (int i = 0; i < cats.length; ++i) {
				checked[i] = mSelection.contains(cats[i]);
			}

			AlertDialog.Builder builder = new AlertDialog.Builder(
					SettingsActivity.this);
			builder.setTitle(R.string.questionCatsLabel);
			builder.setMultiChoiceItems(R.array.questionPrefs, checked, this);
			builder.setCancelable(true);
			builder.setPositiveButton(R.string.ok, this);
			return builder.create();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);

		mPrefs = getSharedPreferences(Tricia.SETTINGS_PREFS_NAME, MODE_PRIVATE);
		mEdit = mPrefs.edit();

		mNameField = (TextView) findViewById(R.id.nameField);
		mNameField.setText(mPrefs.getString("name", ""));

		mEmailField = (TextView) findViewById(R.id.emailField);
		mEmailField.setText(mPrefs.getString("email", ""));

		mAddFriendField = (TextView) findViewById(R.id.addFriendField);

		mServerSpinner = (Spinner) findViewById(R.id.questionServerSpinner);
		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
				R.array.questionServers, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mServerSpinner.setAdapter(adapter);
		mServerSpinner.setSelection(mPrefs.getInt("questionServer", 0));

		String s = mPrefs.getString("questionCats", "");
		QuestionCategorySet questionCats = QuestionCategorySet.unserialize(s);
		mQuestionCatsDialog = new QuestionCatsDialog(questionCats);

		Button questionPrefsButton = (Button) findViewById(R.id.questionCatsButton);
		questionPrefsButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v)
			{
				showDialog(QUESTION_CATS_DIALOG);
			}
		});

		Button addFriendButton = (Button) findViewById(R.id.addFriendButton);
		addFriendButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v)
			{
				new AddFriend().execute();
			}
		});
	}

	private class AddFriend extends AsyncTask<Void, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(Void... params)
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(BASE_URL
					+ "WebServiceTrivial/rest/friends");
			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			pairs.add(new BasicNameValuePair("email", mEmail));
			pairs.add(new BasicNameValuePair("friend_address", mFriendMail));
			try {
				request.setEntity(new UrlEncodedFormEntity(pairs));
				// HttpResponse response = client.execute(request);
				client.execute(request);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		};

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			mEmail = mEmailField.getText().toString();
			mFriendMail = mAddFriendField.getText().toString();
		}

		@Override
		protected void onPostExecute(Boolean result)
		{
		};
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == QUESTION_CATS_DIALOG) {
			return mQuestionCatsDialog.build();
		}

		throw new RuntimeException("Unknown dialog ID " + id);
	}

	@Override
	protected void onPause()
	{
		super.onPause();

		mEdit.putString("name", mNameField.getText().toString());
		mEdit.putString("email", mEmailField.getText().toString());
		mEdit.putInt("questionServer", mServerSpinner.getSelectedItemPosition());
		mEdit.putString("questionCats", mQuestionCatsDialog.getSelection()
				.serialize());
		mEdit.commit();
	}
}
